package com.wwwc.index.web.servlet;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.security.*;
import java.io.*;
import java.net.*;

import javax.imageio.*;
import java.awt.image.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;
//import com.wwwc.index.web.database.*;
import com.wwwc.index.web.ejb.*;

public class UploadFileServlet extends HttpServlet
{
    public void doPost(HttpServletRequest request,  HttpServletResponse response) {
	PrintWriter          out = null;
	DataInputStream       in = null;
	FileOutputStream fileOut = null;
	HttpSession session = request.getSession();
	
	String user_ip      = request.getRemoteAddr();
	String page_head    = request.getHeader("Referer");

	response.setContentType("text/html");

	try {
	    out = response.getWriter();
	    ResourceBundle SystemInfo = (ResourceBundle)session.getAttribute("SystemInfo");
	    if (SystemInfo == null) {
		return;
	    }

	    String local_ips = SystemInfo.getString("3wcenter.local_ips");
	    //String database  = SystemInfo.getString("3wcenter.database");
	    //String main_page = SystemInfo.getString("3wcenter.main_page");
	    //String max_rows  = SystemInfo.getString("3wcenter.content.max_rows");
	    String post_home = SystemInfo.getString("3wcenter.default.post.home");
	    String max_size  = SystemInfo.getString("3wcenter.default.post.upload.image.max_size");

	    String contentType = request.getContentType();

	    if(contentType != null && contentType.indexOf("multipart/form-data") != -1) {
		
		in = new DataInputStream(request.getInputStream());
		int formDataLength = request.getContentLength();
		
		if (formDataLength > Integer.parseInt(max_size)) {
		    out.println("Your file size is ["+formDataLength+"]. Max size allowed is["+max_size+"].");
		    return;
		}

		byte dataBytes[]  = new byte[formDataLength];
		int bytesRead      = 0;
		int totalBytesRead = 0;
		int sizeCheck      = 0;
		    
		while (totalBytesRead < formDataLength) {
		    bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
		    totalBytesRead += bytesRead;
		}

		String file  = new String(dataBytes);
		String parameter1 = file.substring(file.indexOf("parameter1\"")+15);
		parameter1 = parameter1.substring(0, parameter1.indexOf("\n")-1);

		UploadFileBean fbean = (UploadFileBean)session.getAttribute("uploadFileBean"+parameter1);

		if(fbean == null) {
		    return;
		}

		String file_dir   = fbean.getFileDir();
		String file_type  = fbean.getFileType();
		int file_size     = fbean.getFileSize();
		int total_allowed = fbean.getTotalFileAllowed();
		int file_uploaded = fbean.getTotalFileLoaded();
		Vector load_file_name_v = fbean.getLoadedFileNameV();
		Vector user_file_name_v = fbean.getUserFileNameV();
		Vector load_file_url_v  = fbean.getLoadedFileUrlV();

		if(file_dir == null || file_type == null || user_file_name_v == null || 
		   load_file_name_v == null || load_file_url_v == null) {
		    return;
		}

		File fd = new File(post_home+"/"+file_dir);
		if (!fd.exists()) {
		    fd.mkdirs();
		}

		StringBuffer rbf = new StringBuffer(); 
		rbf.append("<SCRIPT>");
		rbf.append("parent.document."+fbean.getFormName()+".submit();");
		rbf.append("</SCRIPT>");

		int    lastIndex = contentType.lastIndexOf("=");
		String boundary  = contentType.substring(lastIndex+1, contentType.length());

		String user_file_name = file.substring(file.indexOf("filename=\"")+10);
		user_file_name = user_file_name.substring(0, user_file_name.indexOf("\n"));
		user_file_name = user_file_name.substring(user_file_name.lastIndexOf("\\")+1, user_file_name.indexOf("\""));

		int pos; //position in upload file
		//find position of upload file section of request
		pos = file.indexOf("filename=\"");
		//find position of content-disposition line
		pos = file.indexOf("\n",pos)+1;
		//find position of content-type line
		pos = file.indexOf("\n",pos)+1;
		//find position of blank line
		pos = file.indexOf("\n",pos)+1;
		
		///////////////////////////////////////////////////////////////////////////////////////
		// find the location of the next boundary marker
		// (marking the end of the upload file data)
		///////////////////////////////////////////////////////////////////////////////////////

		int boundaryLocation = file.indexOf(boundary,pos)-4;

		if( boundaryLocation < 5) {
		    dataBytes = null;
		    file      = null;
		    fbean.setMessage("Loading File Error!");
		    out.println(rbf);
		    return;
		}

		String fileName = null;
		if(file_type.equals("IMAGES")) {
		    if(!(user_file_name.toUpperCase().endsWith(".GIF")  || 
			 user_file_name.toUpperCase().endsWith(".JPG")  || 
			 user_file_name.toUpperCase().endsWith(".JPEG") ||
			 user_file_name.toUpperCase().endsWith(".BMP")  ||
			 user_file_name.toUpperCase().endsWith(".DIB")
			 )) {
			dataBytes = null;
			file      = null;
			fbean.setMessage("Please select *.jpg, *.jpeg, *.gif, or *.bmp file only!");
			out.println(rbf);
			return;
		    }
		    else {
			fileName = System.currentTimeMillis()+user_file_name.substring(user_file_name.lastIndexOf("."));
		    }
		}
		else {
		    dataBytes = null;
		    file      = null;
		    fbean.setMessage("File type "+file_type+" not found!");
		    out.println(rbf);
		    return;
		}

		//////////////////////////////////////////////////////////////////////////////
		// before save file, make sure to check everything
		/////////////////////////////////////////////////////////////////////////////
		if(user_file_name.length()>250) {
		    dataBytes = null;
		    file      = null;
		    fbean.setMessage("File name is too long!");
		    out.println(rbf);
		    return;
		}

		if(user_file_name_v.contains(user_file_name)) {
		    dataBytes = null;
		    file      = null;
		    fbean.setMessage("File "+user_file_name+" has been uploaded.");
		    out.println(rbf);
		    return;
		}

		//////////////////////////////////////////////////////////////////////////////
		//instantiate file output stream
		//////////////////////////////////////////////////////////////////////////////

		File f = new File(fd.getPath(), fileName);
		int m=0;
		while(f.isFile()) {
		    f = new File(fd.getPath(), (System.currentTimeMillis()-1)+"");
		    m++;
		    if(m>20) {
			fbean.setMessage("Upload File Error!");
			out.println(rbf);
			return;
		    }
		}

		fileOut = new FileOutputStream(f.getPath());
		if(boundaryLocation < pos) {
		    fileOut.write(dataBytes, pos, (dataBytes.length-pos-1));
		}
		else {
		    fileOut.write(dataBytes,pos,(boundaryLocation-pos));
		}

		in.close();
		fileOut.close();
		if(f.length()==0) {
		    f.delete();
		    fbean.setMessage("Upload File Error!");
		    out.println(rbf);
		    return;
		}

		String file_url = null;
		if(user_ip.startsWith(local_ips)) {
		    file_url = "http://192.168.1.103/posts/"+file_dir+"/"+f.getName();
		}
		else {
		    file_url = "http://3wcenter.com/posts/"+file_dir+"/"+f.getName();
		}

		load_file_url_v.add(file_url);
		user_file_name_v.add(user_file_name);
		load_file_name_v.add(f.getName());

		fbean.setTotalFileLoaded(file_uploaded+1);
		fbean.setLoadedFileNameV(load_file_name_v);
		fbean.setUserFileNameV(user_file_name_v);
		fbean.setLoadedFileUrlV(load_file_url_v);
		fbean.setMessage("");
		session.setAttribute("uploadFileBean"+parameter1, fbean);
		out.println(rbf);
	    }
	}
	catch(Exception e) {
	    System.out.println("UploadFileServlet:POST:"+e);
	    return;
	}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
    {
	PrintWriter out = response.getWriter();
	String user_ip = request.getRemoteAddr();
	HttpSession session = request.getSession(true);
	response.setContentType("text/html");

	String group_id = request.getParameter("group_id");
	if(group_id==null) {
	    System.out.println("UploadFileServlet:Error:group_id==null");
	    return;
	}

	UploadFileBean fbean = (UploadFileBean)session.getAttribute("uploadFileBean"+group_id);

	if(fbean == null) {
	    fbean = new UploadFileBean();
	    String file_dir    = request.getParameter("file_dir");
	    String file_type   = request.getParameter("file_type");
	    String file_size   = request.getParameter("file_size");
	    String total_files = request.getParameter("total_files");
	    String form_name   = request.getParameter("form_name");

	    if(file_dir == null || file_type == null || file_size == null || 
	       total_files == null || form_name == null || group_id == null) {
		out.println("Error:Upload File:101");
		return;
	    }

	    fbean.setFileDir(file_dir);
	    fbean.setFileType(file_type);
	    fbean.setFileSize(file_size);
	    fbean.setFormName(form_name);
	    fbean.setTotalFileAllowed(total_files);
	    fbean.setTotalFileLoaded(0);
	    fbean.setLoadedFileNameV(new Vector());
	    fbean.setUserFileNameV(new Vector());
	    fbean.setLoadedFileUrlV(new Vector());
	    session.setAttribute("uploadFileBean"+group_id, fbean);
	}
	else {
	    fbean = (UploadFileBean)session.getAttribute("uploadFileBean"+group_id);
	}

	StringBuffer sbf = null;	
	
	if(fbean.getTotalFileAllowed() > fbean.getTotalFileLoaded()){
	    String message = fbean.getMessage();
	    sbf = new StringBuffer();
	    sbf.append("<HTML><HEAD><TITLE>Upload form</TITLE>");
	    sbf.append("</HEAD><BODY>");
	
	    if(message != null && message.length()>0) {
		sbf.append("<img src=/images/star.gif border=0>"+message);
	    }

	    sbf.append("<FORM method=post ENCTYPE=multipart/form-data action=UploadFileServlet>");
	    sbf.append("<TABLE style='font-size:10pt' width=100%>");
	    sbf.append("<TR>");
	    sbf.append("<TD>");
	    sbf.append("<input type='file' name='filename' value='' maxLength=250 size=50 style='font-size: 8pt'>");
	    sbf.append("<input type='hidden' name='parameter1' value='"+group_id+"'>");
	    sbf.append("</TD>");
	    sbf.append("<TD align=left>");
	    sbf.append("<input type=submit name=B value=Attach style='font-size: 8pt'>");
	    sbf.append("</TD></TR></TABLE>");
	    sbf.append("</FORM>");
	    sbf.append("</BODY></HTML>");
	    out.println(sbf);
	}
    }
}

